package com.adopapa.nezhacloud.common;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public final class ScriptEnginer {

	private final static ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

	private final static String JAVA_SCRIPT = "javascript";

	public static ScriptEngine getJavaScriptEnginer() {
		return scriptEngineManager.getEngineByName(JAVA_SCRIPT);
	}

	public static Object javaScriptEval(String formulate, String... args) throws ScriptException {
		formulate = formulate.replaceAll("\\s", "");
		if (formulate.indexOf("y") >= 0) {
			formulate = formulate.substring(2);
		}
		StringBuilder scripts = new StringBuilder();
		scripts.append("var x = [];");
		for (String arg : args) {
			scripts.append("x.push(").append(arg).append(");");
		}
		scripts.append(formulate).append(";");
		return getJavaScriptEnginer().eval(scripts.toString());

	}
	
	public static void main(String[] args) throws ScriptException {
		Double data = null;
		String formulate = "x[0]^2";
		String[] params = new String[] {"200"};
		Object result = ScriptEnginer.javaScriptEval(formulate, params);
		if (result instanceof Integer) {
			data = ((int) result) * 1.0;
		} else if (result instanceof Double) {
			data = (Double) result;
		}
		
		System.out.println(data);
		
		
		formulate = "a*b+c";
		formulate = formulate.replace("a", "13");
		formulate = formulate.replace("b", "2");
		formulate = formulate.replace("c", "15");
		
		Object eval = ScriptEnginer.getJavaScriptEnginer().eval(formulate);
		System.out.println(eval);
	}


}
